import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import { showToast, showLoadingToast, closeToast } from 'vant'
// AxiosResponse
class Request {
  private instance: AxiosInstance
  private loading: boolean

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config)
    this.loading = false

    this.instance.interceptors.request.use(
      (config) => {
        if (!this.loading) {
          showLoadingToast({
            message: '加载中...',
            forbidClick: true,
          })
          this.loading = true
        }

        // 添加token
        const token = localStorage.getItem('token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }

        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    this.instance.interceptors.response.use(
      (response) => {
        if (this.loading) {
          closeToast()
          this.loading = false
        }

        const res = response.data
        if (res.code !== 0) {
          showToast(res.message || '请求失败')
          return Promise.reject(new Error(res.message || '请求失败'))
        }
        return res.data
      },
      (error) => {
        if (this.loading) {
          closeToast()
          this.loading = false
        }

        showToast(error.message || '请求失败')
        return Promise.reject(error)
      }
    )
  }

  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.instance.request(config)
  }

  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config)
  }

  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.post(url, data, config)
  }
}

export default new Request({
  baseURL: import.meta.env.VITE_APP_API_BASE_URL,
  timeout: 10000,
})